package com.levelup.cr.client.ui;

import com.google.gwt.core.client.GWT;
import com.google.gwt.user.cellview.client.CellTree;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.view.client.MultiSelectionModel;
import com.google.gwt.view.client.ProvidesKey;
import com.levelup.cr.client.mvc.RepositoryTreeViewModel;
import com.levelup.cr.client.rpc.RepositoryRemoteService;
import com.levelup.cr.client.rpc.RepositoryRemoteServiceAsync;
import com.levelup.cr.model.dto.NodeTransfer;

import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;


/**
 * Created with IntelliJ IDEA.
 * User: denis_zavadsky
 * Date: 9/26/13
 * Time: 7:50 PM
 * To change this template use File | Settings | File Templates.
 */
public class RepositoryTreeWidget extends VerticalPanel {
    private Logger logger = Logger.getLogger("RepositoryTreeWidget");

    final RepositoryRemoteServiceAsync repositoryService = GWT.create(RepositoryRemoteService.class);
    final MultiSelectionModel<NodeTransfer> selectionModel =
            new MultiSelectionModel<NodeTransfer>(KEY_PROVIDER);
    CellTree.Resources res = GWT.create(CellTree.BasicResources.class);

    CellTree cellTree;

    public RepositoryTreeWidget() {
      init();
    }

    private void init(){

        getDefaultNode();

    }

    private void getDefaultNode() {
        String path = "/level1";
        repositoryService.getNodeByPath(path,2,new AsyncCallback<NodeTransfer>() {
            @Override
            public void onFailure(Throwable caught) {
                Window.alert("Error");
            }

            @Override
            public void onSuccess(NodeTransfer result) {
                logger.log(Level.SEVERE,"Node populated: "+ result.getName());
                processNode(result);
            }
        });
    }

    private void processNode(NodeTransfer node){
        logger.log(Level.SEVERE,"Process Node: "+ node.getName());
        NodeTransfer root = new NodeTransfer();
        root.setName("/");
        List<NodeTransfer> rootChilds = new ArrayList<NodeTransfer>();
        rootChilds.add(node);
        root.setChilds(rootChilds);
        cellTree = new CellTree(
                new RepositoryTreeViewModel(selectionModel), root, res);
        if (cellTree!=null)
            logger.log(Level.SEVERE,"Cell Tree Created");
        cellTree.setAnimationEnabled(true);

        this.add(cellTree);
    }

    public static final ProvidesKey<NodeTransfer> KEY_PROVIDER = new ProvidesKey<NodeTransfer>() {
        @Override
        public Object getKey(NodeTransfer item) {
            return item == null ? null : item.getName();
        }
    };
}
